/**
 * 遍历 t('xxx') |  t('xxx', { xxx})生成 json
 **/

import fs from 'fs-extra'
import path from 'node:path'
import ts from 'typescript'
import { fileURLToPath } from 'node:url'

const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)

// 设置项目根目录
const projectRoot = path.resolve(__dirname, '../../')

// 设置要解析的文件扩展名
const fileExtensions = ['.html', '.ts', '.tsx', '.js']

// 设置要过滤的目录，根目录
let ignoredDirectories = ['node_modules', '.git', '.vscode', 'task', 'config', 'dist']
//help 目录 过滤
const brandFolder = path.join(projectRoot, 'src/pages/brand')
const files = fs.readdirSync(brandFolder)
files.forEach((file) => {
	const filePath = path.join(brandFolder, file)
	if (fs.statSync(filePath).isDirectory()) {
		ignoredDirectories.push('brand\\' + file + '\\help')
	}
})

// 存储参数的对象
const paramsObject = {}

const ignoredMap = ignoredDirectories.map((x) => path.join(projectRoot, x))
// 递归遍历目录
function traverseDirectory(dir) {
	const files = fs.readdirSync(dir)

	files.forEach((file) => {
		const filePath = path.join(dir, file)
		const stat = fs.statSync(filePath)

		if (stat.isDirectory()) {
			if (!ignoredMap.includes(filePath)) {
				traverseDirectory(filePath)
			}
		} else {
			processFile(filePath)
		}
	})
}

// 处理文件
function processFile(file) {
	const extension = path.extname(file)

	if (fileExtensions.includes(extension)) {
		const content = fs.readFileSync(file, 'utf8')

		if (extension === '.ts' || extension === '.tsx' || extension === '.js') {
			parseTypeScriptFile(content, file)
		} else if (extension === '.html') {
			parseOtherFile(content)
		}
	}
}

// 解析 TypeScript 文件
function parseTypeScriptFile(content, file) {
	const sourceFile = ts.createSourceFile(file, content, ts.ScriptTarget.ESNext, true)

	function traverse(node) {
		if (node.kind === ts.SyntaxKind.CallExpression) {
			const callExpression = node
			const functionName = callExpression.expression.getText()
			// console.log(functionName, 'functionName')
			if (functionName === 't') {
				const firstArgument = callExpression.arguments[0]
				const secondArgument = callExpression.arguments[1]
				// console.log(callExpression, 'callExpression---------')
				if (
					firstArgument &&
					(firstArgument.kind === ts.SyntaxKind.StringLiteral ||
						firstArgument.kind === ts.SyntaxKind.NoSubstitutionTemplateLiteral)
				) {
					const param = firstArgument.text

					if (param && !paramsObject.hasOwnProperty(param)) {
						paramsObject[param] = param
					}
					if (secondArgument && ts.isObjectLiteralExpression(secondArgument)) {
						secondArgument.properties.forEach((property) => {
							if (
								ts.isPropertyAssignment(property) &&
								ts.isIdentifier(property.name) &&
								property.name.text === 'context'
							) {
								const contextValue = property.initializer.getText(sourceFile)
								if (contextValue) {
									let matches = contextValue.match(/SC\d+/g)
									matches?.forEach((x) => {
										paramsObject[`${param}_${x}`] = param
									})
								}
							}
						})
					}
				} else {
					// 获取节点在源文件中的位置信息
					const position = node.getStart(sourceFile)
					const { line, character } = ts.getLineAndCharacterOfPosition(sourceFile, position)
					console.log(
						`\x1b[31m请确认 ${file} 的 第${line + 1
						}行 字符偏移量 ${character} 的 t 函数是否需要提取？若需要，请手动加入lang.json内\x1b[0m`
					)
					console.log('该 t 函数的第一个入参为 :>> ', firstArgument.getText())
				}
			}
		}
		if (ts.isVariableDeclaration(node)) {
			const variableName = node.name.getText()
			const initializer = node.initializer

			if (initializer && ts.isObjectLiteralExpression(initializer)) {
				// Check if the variable name ends with '_i18n_key'
				if (variableName.endsWith('_i18n_key')) {
					initializer.properties.forEach((property) => {
						if (ts.isPropertyAssignment(property) && ts.isStringLiteral(property.initializer)) {
							const value = property.initializer.text
							if (/[\u4e00-\u9fff]/.test(value) && !value.includes('科达')) {
								paramsObject[value] = value
							}
						}
					})
				}
			}
		}

		if (ts.isBinaryExpression(node)) {
			if (
				ts.isPropertyAccessExpression(node.left) &&
				ts.isIdentifier(node.left.expression) &&
				node.left.expression.text === 'window' &&
				node.left.name.text.endsWith('_i18n_key') &&
				ts.isObjectLiteralExpression(node.right)
			) {
				for (const property of node.right.properties) {
					if (ts.isPropertyAssignment(property) && ts.isStringLiteral(property.initializer)) {
						let value = property.initializer.text
						if (/[\u4e00-\u9fff]/.test(value) && !value.includes('科达')) {
							paramsObject[value] = value
						}
					}
				}
			}
		}

		ts.forEachChild(node, traverse)
	}

	traverse(sourceFile)
}

// 解析其他文件（例如 HTML 文件）
function parseOtherFile(content) {
	const pattern = /\bt\(\s*(['"`])(.*?)\1/g

	let match
	while ((match = pattern.exec(content)) !== null) {
		const param = match[2]
		if (param && !paramsObject.hasOwnProperty(param)) {
			paramsObject[param] = param
		}
	}
}

// 开始遍历项目目录
traverseDirectory(projectRoot)

// 输出到 JSON 文件
console.log('')
console.log('最新中文完整json：./__temp__/lang.json')
const outputFilePath = path.resolve(__dirname, './__temp__/lang.json')
fs.writeFileSync(outputFilePath, JSON.stringify(paramsObject, null, 2))

//对比
let en_json = JSON.parse(fs.readFileSync(path.resolve(__dirname, '../../src/i18n/en/lang.json'), 'utf8'))

let oldhas = {}
let newhas = {}

for (const key in paramsObject) {
	if (en_json[key]) {
		oldhas[key] = en_json[key]
	} else {
		newhas[key] = key
	}
}

console.log('和当前最新的英文版lang.json之间的对比，新增了：./__temp__/lang_add.json')
const newPath = path.resolve(__dirname, './__temp__/lang_add.json')
fs.writeFileSync(newPath, JSON.stringify(newhas, null, 2))

console.log('最新的英文版lang.json存在多余的，可更新为：./__temp__/lang_en.json')
const oldPath = path.resolve(__dirname, './__temp__/lang_en.json')
fs.writeFileSync(oldPath, JSON.stringify(oldhas, null, 2))
